import { Space,Button, message, Divider,Modal } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { PlusOutlined ,ExclamationCircleOutlined} from '@ant-design/icons';
import { queryDeviceAttr, addDeviceAttr, updateDeviceAttr, removeDeviceAttr,batchRemoveDeviceAttr } from '@/services/deviceattr';
const { confirm } = Modal;

import { queryDeviceTypeList} from '@/services/devicetype';
import styles from '@/global.less';


/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: any,resetForm: any,ids:string) => {
  const hide = message.loading('正在添加');
  try {
    console.log(ids)
    await addDeviceAttr({...fields,ids});
    hide();
    resetForm();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateDeviceAttr(fields);
    hide();

    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};

//删除单个
const remove = async (attrId: number) => {
  const hide = message.loading('正在删除');
  try {
    await removeDeviceAttr({ attrId });
    hide();

    message.success('删除成功，正在刷新！');

    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }
};


var attrTypeValueEnum={
  common: { text: '公共变量'},
  special: { text: '特有变量'},
}



const DeviceAttr: React.FC = () => {

const [createModalVisible, handleModalVisible] = useState<boolean>(false);
const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
const [formValues, setFormValues] = useState({});
const [typeEnumValues, setTypeEnumValues] = useState({});
const [typeValues, setTypeValues] = useState<API.DictItem[]>([]);
const [selectedRowKeys,setSelectedRowKeys] = useState<number[]>([]);
const onSelectChange = async (sKeys ) => {
  setSelectedRowKeys(sKeys);

};

//批量删除
const batchRemove = async () => {
const hide = message.loading('正在删除');
try {
  await batchRemoveDeviceAttr({ ids: selectedRowKeys.join(',')});
  setSelectedRowKeys([]);
  hide();
  message.success('删除成功，正在刷新！');
  return true;
} catch (error) {
  hide();
  message.error('删除失败请重试！');
  return false;
}
}
const actionRef = useRef<ActionType>();
  const columns: ProColumns[] = [
{
      title: '设备类型',
      dataIndex: 'deviceTypeId',
      valueEnum: typeEnumValues,
    },
    {
      title: '序号',
      search: false,
      dataIndex: 'orderNo',
    },
    {
      title: '变量类别',
      dataIndex: 'attrType',
      valueEnum:attrTypeValueEnum
    },
    {
      title: '变量名称',
      search: false,
      dataIndex: 'dispalyName',
    },
    {
      title: '页面展示名称',
      dataIndex: 'browseName',
    },
    {
      title: '单位',
      search: false,
      dataIndex: 'unit',
    },
    {
      title: '数据类型',
      search: false,
      dataIndex: 'dataType',
    },
    {
      title: '最大值',
      search: false,
      dataIndex: 'maxValue',
    },
    {
      title: '最小值',
      search: false,
      dataIndex: 'minValue',
    },
    {
      title: '是否启用',
      dataIndex: 'useState',
      valueType: 'radio',
      valueEnum: {
        1: { text: '启用'},
        0: { text: '禁用'},
      }
    },
    // {
    //   title: '创建时间',
    //   search: false,
    //   dataIndex: 'createTime',
    // },
    // {
    //   title: '更新时间',
    //   search: false,
    //   dataIndex: 'updateTime',

    // },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => (
      <>
        <a
          key="editable"
          onClick={async () => {
            handleUpdateModalVisible(true);
            setFormValues(record);
          }}
        >
          编辑
        </a>
        <Divider type="vertical" />
        <a onClick={() => {
          confirm({
            title: '您确定要删除吗?',
            icon: <ExclamationCircleOutlined />,
            async onOk() {
              await remove(record.attrId);
              actionRef.current?.reload();
            },
            onCancel() {
              console.log('Cancel');
            },
          });
        }}
        >
          删除
        </a>
        </>
      )
    },
  ];
  useEffect(() => {
    const setSelectData = async () => {
      const deviceType = await queryDeviceTypeList();
      let tdata = {};
      if (deviceType && deviceType.length > 0) {
        deviceType.forEach(item => {
          tdata[item.typeId] = { text: item.typeName};
        });
      }

      console.log(tdata)
      setTypeEnumValues(tdata);
      setTypeValues(deviceType);

    } 
    setSelectData();
  }, []);


  return (
    <>
      <ProTable
        rowKey="attrId"
        toolBarRender={(action, { selectedRows }) => [
          <Button icon={<PlusOutlined />} type="primary"  className={styles.addBtn} onClick={() => handleModalVisible(true)}>
            新增
          </Button>,
       
        ]}
        rowSelection={{selectedRowKeys,onChange: onSelectChange}}
        tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
        tableAlertOptionRender={() => {
          return (
            <Space size={16}>
              <a  onClick={() => {
              confirm({
                title: '您确定要批量删除吗?',
                icon: <ExclamationCircleOutlined />,
                async onOk() {
                  await batchRemove();
                  actionRef.current?.reload();
                },
                onCancel() {
                  console.log('Cancel');
                },
              });
            }} >批量删除</a>
              {/* <a>导出数据</a> */}
            </Space>
          );
        }}
        search={{
          labelWidth: 'auto',
        }}
        options={false}
        actionRef={actionRef}
      
        columns={columns}
        request={(params) => queryDeviceAttr(params)}
      />
      <CreateForm
        onSubmit={async (value,resetForm,ids) => {
          const success = await handleAdd(value,resetForm,ids);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        typeEnumValues={typeEnumValues}
        devicetype={typeValues}
      />
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
          devicetype={typeValues}
        />
      ) : null}
    </>
  );
};

export default DeviceAttr;



